package com.coze.lg.cozeagent.controller.oldtest;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class socketWebSocketSpringBoot extends TextWebSocketHandler {

    public socketWebSocketSpringBoot () {
        System.out.println("--------------------------------------socketWebSocketSpringBoot <UNK>");
    }

    // 存储所有连接的会话
    private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 当新连接建立时被调用
        sessions.add(session);
        System.out.println("新客户端连接，当前连接数: " + sessions.size());
        session.sendMessage(new TextMessage("欢迎连接到WebSocket服务！"));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理客户端发送的消息
        String payload = message.getPayload();
        System.out.println("收到消息: " + payload);

        // 向所有连接的客户端广播消息
        broadcast("用户" + session.getId() + "说: " + payload);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 当连接关闭时被调用
        sessions.remove(session);
        System.out.println("客户端断开连接，当前连接数: " + sessions.size());
    }

    // 广播消息给所有连接的客户端
    private void broadcast(String message) {
        for (WebSocketSession session : sessions) {
            try {
                if (session.isOpen()) {
                    session.sendMessage(new TextMessage(message));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
